package cc.android.testapp.xp.hooker.adblock.util;

import android.net.Uri;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import cc.android.testapp.TAContentProvider;
import cc.android.testapp.cfg.Config;
import cc.android.testapp.cfg.ConfigHelper;
import cc.android.testapp.util.CLog;
import cc.commons.util.FileUtil;

public class ADBCfg implements TAContentProvider.TAReslove {

    public static String PATH_SAVE_RULE = "/save_rule";
    public static String PATH_READ_RULE = "/read_rule";
    public static String KEY_WHITLE_NAME = "white_name";
    public static final String SAVEDIR = "/data/data/" + Config.MODULE_PACKAGE_NAME + "/files/AdBlock/";

    public static void registerResolve() {
        ADBCfg t = new ADBCfg();
        TAContentProvider.registerReslove(ADBCfg.PATH_SAVE_RULE, t);
        TAContentProvider.registerReslove(ADBCfg.PATH_READ_RULE, t);
    }

    public static String getRule(String pAct) {
        return ConfigHelper.resolveConfig(PATH_READ_RULE, "an", pAct);
    }

    public static String saveRule(String pAct, String pRule) {
        return ConfigHelper.resolveConfig(PATH_SAVE_RULE, new String[]{"an", "data"}, pAct, pRule);
    }

    @Override
    public String handleRequest(String pPName, String pType, Uri pUri) {
        String tActName = pUri.getQueryParameter("an");

        if (pType.equals(ADBCfg.PATH_SAVE_RULE)) {
            String tSData = pUri.getQueryParameter("data");
            if (tSData != null)
                saveData(SAVEDIR + "rule/", pPName, tActName, tSData);

        } else if (pType.equals(ADBCfg.PATH_READ_RULE)) {
            return readData(SAVEDIR + "rule/", pPName, tActName);
        }
        return "";
    }

    private String readData(String pPath, String pDir, String pFile) {
        File file = new File(pPath, pDir + "/" + pFile);
        try {
            if (file.exists()) {
                return FileUtil.readContent(file, "UTF-8");
            }
            if (file.getParentFile().mkdirs()) file.createNewFile();
            return "";
        } catch (IOException e) {
            CLog.log("Error on read file: " + file.getAbsolutePath(), e);
            return null;
        }
    }

    private void saveData(String str, String str2, String str3, String str4) {
        try {
            FileUtil.writeData(new File(str, str2 + "/" + str3), str4.getBytes(StandardCharsets.UTF_8));
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    public static File getAppRuleConfig(String pPackage) {
        return new File(SAVEDIR, "rule/" + pPackage);
    }

    public static List<String> getWhiteList() {
        File file = new File(SAVEDIR, "white_list");
        ArrayList<String> tList = new ArrayList<>();
        try {
            if (file.exists()) {
                String tStr = FileUtil.readContent(file, "UTF-8");
                JSONArray tJson = new JSONArray(tStr.isEmpty() ? "[]" : tStr);
                for (int i = tJson.length() - 1; i >= 0; i--) {
                    tList.add(String.valueOf(tJson.get(i)));
                }
            } else {
                if (file.getParentFile().mkdirs()) file.createNewFile();
            }
        } catch (JSONException | IOException e) {
            e.printStackTrace();
        }

        tList.add("com.guoshi.httpcanary");
        return tList;
    }

    public static String getCfgNode() {
        return "adb";
    }

}
